package com.sun.module_category.ui

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.sun.module_base.app.BaseViewModel
import com.sun.module_base.app.ResultState
import com.sun.module_category.net.HttpRepository
import com.sun.module_common.model.Article
import com.sun.module_common.model.ListWrapper
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

/**
 *@author:sunc
 *@time :2025/8/15 9:06
 *@desc: 描述
 */
@HiltViewModel
class CategoryItemViewModel @Inject constructor(private val httpRepository: HttpRepository) :
    BaseViewModel() {

    private var _categoryFlow =
        MutableStateFlow<CategoryItemState>(ResultState.Loading())
    val categoryFlow = _categoryFlow.asStateFlow()

    //    init {
//        getProjectCategory()
//    }
    var page by mutableIntStateOf(0)

    private val _isRefresh = mutableStateOf(false)
    val isRefresh: Boolean get() = _isRefresh.value

    private val _isLoadMore = mutableStateOf(false)
    val isLoadMore: Boolean get() = _isLoadMore.value

    fun getCategoryList(cid: Int) {
        launchUI({ httpRepository.getCategoryList(page, cid) }, _categoryFlow, onCompletion = {
            _isRefresh.value = false
            _isLoadMore.value = false
        })
    }

    fun refresh(cid: Int) {
        _isRefresh.value = true
        page = 0
        getCategoryList(cid)

    }

    fun loadMore(cid: Int) {
        _isLoadMore.value = true
        page++
        getCategoryList(cid)
    }
}

typealias CategoryItemState = ResultState<ListWrapper<Article>?>